﻿using Azure.Core;
using DataModels.Dto;
using DataModels.Dto.WorkOrder;
using DataModels.Entities.Base;
using DataModels.Entities.House;
using DataModels.Entities.WorkOrder;
using DataModels.Enums.WorkOrder;
using Dm;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.VisualBasic;
using Services.AuthCore;
using Services.House;
using SqlSugar;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Utils;
using WeChatServices;
using static DataModels.Enums.GeneralEnum;

namespace Services.WorkOrder
{
    public class WorkOrderRapidService(SqlSugarClient db, UserService UserService, OauthService oauthService, IConfiguration configuration) : BaseService(db)
    {
        protected readonly UserService _userService = UserService;
        protected readonly OauthService _oauthService = oauthService;
        private readonly WeChatMessageHandler _messageHandler = new WeChatMessageHandler(configuration, oauthService);

        /// <summary>
        /// 记录变更历史
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private Guid RecordHistory(WorkOrderRapid model,string ReasonForChangeDescription="")
        {
            // 记录工单变更历史
            WorkOrderRapidHistory history = new()
            {
                UUID = Guid.NewGuid(), // 为历史记录生成新的UUID
                WorkOrderUUID = model.UUID,
                OrderNo = model.OrderNo,
                HouseUUID = model.HouseUUID,
                Phone = model.Phone,
                Title = model.Title,
                Description = model.Description,
                TypeId = model.TypeId,
                Type = model.Type,
                Priority = model.Priority,
                Status = model.Status,
                ActualResolveTime = model.ActualResolveTime,
                CreateTime = DateTime.Now,
                UpdateTime = model.UpdateTime,
                CloseTime = model.CloseTime,
                RequesterId = model.RequesterId,
                ProcessorId = model.ProcessorId,
                ProjectId = model.ProjectId,
                SatisfactionScore = model.SatisfactionScore,
                SatisfactionComment = model.SatisfactionComment,
                ReasonForChange = model.ReasonForChange,
                ReasonForChangeDescription = ReasonForChangeDescription,
                Urgent = model.Urgent
            };

            db.Insertable(history).ExecuteCommand();
            return history.UUID;
        }

        /// <summary>
        /// 获取工单类型
        /// </summary>
        /// <returns></returns>
        public ResponseModel GetWorkOrderType(int ParentId = -1, string WhereToUse = "jihekuaisu")
        {
            // 查询所有启用的工单类型
            var allTypes = db.Queryable<WorkOrderType>()
                             .Where(x => x.Status == Status.Enable)
                             .Where(x => x.WhereToUse == WhereToUse)
                             .ToList();

            // 递归构建树结构
            List<WorkOrderTypeTree> BuildTree(List<WorkOrderType> nodes, int? parentId)
            {
                return nodes
                    .Where(x => x.ParentId == parentId)
                    .Select(x => new WorkOrderTypeTree
                    {
                        Id = x.Id,
                        Name = x.Name,
                        ParentId = x.ParentId,
                        Children = BuildTree(nodes, x.Id)
                    })
                    .ToList();
            }

            // 返回树形结构
            var data = BuildTree(allTypes, ParentId == -1 ? 0 : ParentId);
            return Success(data);
        }


        /// <summary>
        /// 创建快速工单
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public async Task<ResponseModel> CreateRapidWorkOrder(CreateWorkOrderInfo info)
        {
            try
            {
                var house = db.Queryable<HousingBasic>().Where(x => x.HouseId == info.HouseId).First();
                if (house == null)
                {
                    return Error("房屋不存在",400);
                }
                WorkOrderType wot = db.Queryable<WorkOrderType>().Where(wot => wot.Id == info.TypeId).First();
                if (wot == null)
                {
                    return Error("工单类型不存在",400);
                }
                var model = new WorkOrderRapid
                {
                    TypeId = info.TypeId,
                    Type = wot.Name,
                    HouseUUID = house.UUID,
                    Phone = info.Phone,
                    Description = info.Description,
                    RequesterId = UserUUID,
                    ProjectId = info.ProjectId,
                    DoorTime = info.DoorTime
                };
                db.BeginTran();
                WorkOrderRapid wo = db.Insertable(model).ExecuteReturnEntity();
                wo.ReasonForChange = "提单";
                RecordHistory(wo);
                info.Urls.Select(url => new Attachment
                {
                    BusinessId = wo.UUID,
                    Url = url,
                    CreatedBy = UserUUID
                }).ToList().ForEach(a =>
                {
                    db.Insertable(a).ExecuteCommand();
                });
                db.CommitTran();

                automaticDispatch(wo);

                return Success("提交成功");
            }
            catch
            {
                db.RollbackTran();
                return Error("提交失败");
            }
        }

        public async Task automaticDispatch(WorkOrderRapid wo)
        {
            // 自动派单 （不更改状态，只发消息给接单人组）
            // 通过类型找到对应的接单人组 
            List<Customer> pcm2 = new List<Customer>();
            WorkOrderType wot = db.Queryable<WorkOrderType>().Where(wot => wot.Id == wo.TypeId).First();
            string ordertypeonename = "工程类";
            if (wot.ParentId == 47)
            {
                ordertypeonename = "工程类";
                //工程类
                ResponseModel rm2 = _userService.GetObtainUsers_owners_through_role("济和医院工单接单员工程类");
                if (rm2.Data != null)
                {
                    pcm2 = (List<Customer>)rm2.Data;
                }
            }
            else if (wot.ParentId == 1043)
            {
                ordertypeonename = "医疗设备类";
                //医疗设备类
                ResponseModel rm2 = _userService.GetObtainUsers_owners_through_role("济和医院工单接单员医疗设备类");
                if (rm2.Data != null)
                {
                    pcm2 = (List<Customer>)rm2.Data;
                }
            }
            else
            {
                ordertypeonename = "清洁秩序类";
                //清洁秩序类
                ResponseModel rm2 = _userService.GetObtainUsers_owners_through_role("济和医院工单接单员");
                if (rm2.Data != null)
                {
                    pcm2 = (List<Customer>)rm2.Data;
                }
            }
            //发送模板消息
            string appType = "fwh";
            string paidanren = "";
            try
            {
                var accessToken = await _oauthService.GetAccessToken(appType);
                string templateId = _messageHandler.GetTemplateMessageID("工单派送通知");

                foreach (Customer item in pcm2)
                {
                    paidanren += item.Name + "、";
                    string openId = item.mpopen_id; // "用户的openId 服务号";
                    if (string.IsNullOrWhiteSpace(openId))
                        continue;
                    //// 构造模板消息数据，根据模板要求设置
                    var fieldValues = new Dictionary<string, string>
                        {
                            {"character_string13", wo.OrderNo}, // 修复为空的字段
                            {"phone_number4", wo.Phone},
                            {"thing8", wo.Description},
                            {"phrase7", ordertypeonename}
                        };
                    string pagePath = ""; //点击模板跳转页面
                    string dataJson = _messageHandler.BuildTemplateMessageWithMultipleKeywords(openId, templateId, pagePath, fieldValues);

                    var result = _messageHandler.SendTemplateMessage(accessToken, openId, templateId, dataJson);
                }
            }
            catch (Exception)
            {

            }
            //工单历史添加 自动派单说明
            wo.ReasonForChange = "自动派单：" + paidanren;
            RecordHistory(wo);
        }

        public (Boolean, object) CheckWorkOrder1(Guid WorkOrderId)
        {
            var wo = db.Queryable<WorkOrderRapid>().Where(wo => wo.UUID == WorkOrderId).First();
            if (wo == null)
            {
                return (false, "未查询到工单信息");
            }
            switch (wo.Status)
            {
                case WorkOrderRapidStatus.New:
                    break;
                case WorkOrderRapidStatus.Assigned:
                    break;
                case WorkOrderRapidStatus.Processing:
                    break;
                case WorkOrderRapidStatus.WaitingForFeedback:
                    break;
                case WorkOrderRapidStatus.Resolved:
                    break;
                case WorkOrderRapidStatus.Closed:
                    return (false, $"工单：{wo.OrderNo}，{WorkOrderRapidStatus.Closed.GetDescription()}");
                case WorkOrderRapidStatus.Cancelled:
                    return (false, $"工单：{wo.OrderNo}，{WorkOrderRapidStatus.Cancelled.GetDescription()}");
                default:
                    break;
            }
            return (true, wo);
        }

        public (Boolean, object) CheckWorkOrder(Guid WorkOrderId)
        {
            var wo = db.Queryable<WorkOrderRapid>().Where(wo => wo.UUID == WorkOrderId).First();
            if (wo == null)
            {
                return (false, "未查询到工单信息");
            }
            switch (wo.Status)
            {
                case WorkOrderRapidStatus.New:
                    break;
                case WorkOrderRapidStatus.Assigned:
                    break;
                case WorkOrderRapidStatus.Processing:
                    break;
                case WorkOrderRapidStatus.WaitingForFeedback:
                    break;
                case WorkOrderRapidStatus.Resolved:
                    return (false, $"工单：{wo.OrderNo}，{WorkOrderRapidStatus.Resolved.GetDescription()}");
                case WorkOrderRapidStatus.Closed:
                    return (false, $"工单：{wo.OrderNo}，{WorkOrderRapidStatus.Closed.GetDescription()}");
                case WorkOrderRapidStatus.Cancelled:
                    return (false, $"工单：{wo.OrderNo}，{WorkOrderRapidStatus.Cancelled.GetDescription()}");
                default:
                    break;
            }
            return (true, wo);
        }

        /// <summary>
        /// 工单加急
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public ResponseModel UrgentWorkOrder(UrgentWorkOrder info)
        {
            var re = CheckWorkOrder(info.WorkOrderId);
            if (!re.Item1)
            {
                return Error(re.Item2.ToString());
            }

            WorkOrderRapid wo = (WorkOrderRapid)re.Item2;

            if (wo.Urgent == DataModels.Enums.GeneralEnum.Status.Enable)
            {
                return Error("工单已经是加急状态");
            }
            RecordHistory(wo);
            wo.Urgent = DataModels.Enums.GeneralEnum.Status.Enable;
            db.Updateable(wo).ExecuteCommand();

            return Success("已加急");
        }

        /// <summary>
        /// 更新快速工单状态
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public ResponseModel UpdateRapidWorkOrderRapidStatus(CancelledWorkOrderRapid info)
        {
            var re = CheckWorkOrder1(info.WorkOrderId);
            if (!re.Item1)
            {
                return Error(re.Item2.ToString());
            }

            WorkOrderRapid wo = (WorkOrderRapid)re.Item2;
            wo.Status = info.Status;
            if ((int)info.Status == 1)
            {
                if (info.ProcessorId == Guid.Empty || info.ProcessorId == null)
                {
                    return Error("更改为转单时请提交接单人ID", 400);
                    //return Error("更改为已接单时请提交接单人ID", 400);

                }
                wo.ProcessorId = info.ProcessorId;

                wo.ReasonForChange = "已转单";
                var c1 = db.Queryable<Customer>().Where(wo => wo.UUID == info.ProcessorId).First();
                RecordHistory(wo, $"转单给{c1.Name}({c1.Tel1})");
            }
            if ((int)info.Status == 4)
            {
                //如果是从转单来的就有接单人id
                if (info.ProcessorId == Guid.Empty || info.ProcessorId == null)
                    return Error("更改为已处理时请提交处理人ID", 400);
                wo.ProcessorId = info.ProcessorId;

                if (string.IsNullOrWhiteSpace(info.ReasonForChange))
                    return Error("更改为已处理(待审核)时候请提交解决方案", 400);
                wo.ReasonForChange = info.ReasonForChange;

                if (info.expenseAmount < 0)
                    return Error("更改为已处理(待审核)时候请提交处理金额", 400);
                wo.expenseAmount = info.expenseAmount;
                wo.MaterialUUID = info.MaterialUUID;
                wo.material = info.material;
                wo.ActualResolveTime = DateTime.Now;

                info.Urls.Select(url => new Attachment
                {
                    BusinessId = wo.UUID,
                    Url = url,
                    Status = 0,
                    CreatedBy = UserUUID
                }).ToList().ForEach(a =>
                {
                    db.Insertable(a).ExecuteCommand();
                });
            }
            if ((int)info.Status == 0)
            {
                if (info.ProcessorId == Guid.Empty || info.ProcessorId == null)
                    return Error("更改为驳回时请提交处理人ID", 400);

                wo.ReasonForChange = "已驳回";
                var c1 = db.Queryable<Customer>().Where(wo => wo.UUID == info.ProcessorId).First();
                RecordHistory(wo, $"{c1.Name}({c1.Tel1}) 已驳回");

                wo.expenseAmount = 0;
                wo.ReasonForChange = "";
                automaticDispatch(wo);
            }
            wo.UpdateTime = DateTime.Now;
            db.Updateable(wo).ExecuteCommand();
            if ((int)info.Status == 4)
            {
                wo.ReasonForChange = "已处理";
                var c1 = db.Queryable<Customer>().Where(wo => wo.UUID == info.ProcessorId).First();
                RecordHistory(wo, $"{c1.Name}({c1.Tel1}) 已处理");
            }
            if ((int)info.Status == 5)
            {
                if (info.ProcessorId == Guid.Empty || info.ProcessorId == null)
                    return Error("更改为已完成时请提交处理人ID", 400);

                wo.ReasonForChange = "已完成";
                var c1 = db.Queryable<Customer>().Where(wo => wo.UUID == info.ProcessorId).First();
                RecordHistory(wo, $"{c1.Name}({c1.Tel1}) 已审核完成");
            }
            return Success("已更新");
        }

        /// <summary>
        /// 取消工单
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public ResponseModel CancelledWorkOrder(CancelledWorkOrder info)
        {
            var re = CheckWorkOrder(info.WorkOrderId);
            if (!re.Item1)
            {
                return Error(re.Item2.ToString());
            }

            WorkOrderRapid wo = (WorkOrderRapid)re.Item2;
            RecordHistory(wo);
            wo.Status = WorkOrderRapidStatus.Cancelled;
            wo.ReasonForChange = info.ReasonForChange;
            wo.UpdateTime = DateTime.Now;

            db.Updateable(wo).ExecuteCommand();

            return Success("已撤销");
        }

        /// <summary>
        /// 评价工单
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public ResponseModel ResolvedWorkOrder(ResolvedWorkOrder info)
        {
            var re = CheckWorkOrder(info.WorkOrderId);
            if (!re.Item1)
            {
                return Error(re.Item2.ToString());
            }

            WorkOrderRapid wo = (WorkOrderRapid)re.Item2;

            if (wo.Status != WorkOrderRapidStatus.WaitingForFeedback)
            {
                return Error("只能评价待评价的工单", 400);
            }

            wo.Status = WorkOrderRapidStatus.Resolved;
            wo.SatisfactionComment = info.SatisfactionComment;
            wo.UpdateTime = DateTime.Now;

            db.Updateable(wo).ExecuteCommand();

            return Success("评价完成");
        }

        /// <summary>
        /// 获取快速工单列表
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public ResponseModel GetWorkOrder(GetWorkOrderRapidInfo info)
        {
            if (info.WorkOrderId != Guid.Empty)
            {
                List<Attachment> Attachments = db.Queryable<Attachment>().Where(atc => atc.BusinessId == info.WorkOrderId).ToList();
                List<GetWorkOrderRapidDto> wodre = db.Queryable<WorkOrderRapid, Projects, Customer, Material, WorkOrderType>((wot, p, c, ml, wott) => new object[]
                {
                    JoinType.Left,wot.ProjectId == p.UUID,
                    JoinType.Left,wot.ProcessorId == c.UUID,
                    JoinType.Left,wot.MaterialUUID ==ml.UUID,
                    JoinType.Left,wot.TypeId ==wott.Id
                })
                    .LeftJoin<WorkOrderType>((wot, p, c, ml, wott, wott1) => wott.ParentId == wott1.Id)

                    .LeftJoin<Customer>((wot, p, c, ml, wott, wott1, c2) => wot.RequesterId == c2.UUID)
                    .LeftJoin<CustomerHouseRelation>((wot, p, c, ml, wott, wott1,c2,chr) => chr.CustId == c2.CustId)
                    .Where(wot => wot.UUID == info.WorkOrderId)
                    .Select((wot, p, c, ml, wott, wott1,c2,chr) => new GetWorkOrderRapidDto
                    {
                        WorkOrderId = wot.UUID,
                        ProjectName = p.ProjectName,
                        Type = wott1.Name + "-" + wot.Type,
                        Status = wot.Status,
                        Urgent = wot.Urgent,
                        CreateTime = wot.CreateTime,
                        OrderNo = wot.OrderNo,
                        Description = wot.Description,
                        ReasonForChange = wot.ReasonForChange,
                        Phone = wot.Phone,
                        CreateName = c2.Name,
                        ProcessorName = c.Name,
                        ProcessorPhone = c.Tel1,
                        expenseAmount = wot.expenseAmount,
                        material = wot.material,
                        FullAddress = chr.ResourceName
                    })
                    .ToList()
                    ;

                List<WorkOrderRapidHistory> woth = db.Queryable<WorkOrderRapidHistory>().Where(wot => wot.WorkOrderUUID == info.WorkOrderId).OrderBy(wot => wot.CreateTime, OrderByType.Desc).ToList();

                foreach (var wot in wodre)
                {
                    wot.Urls = Attachments.Where(atc => atc.Status == Status.Enable).Select(atc => atc.Url).ToList();
                    wot.yiwagchenUrls = Attachments.Where(atc => atc.Status == Status.Disable).Select(atc => atc.Url).ToList();
                    wot.Progress = [.. woth.Select(dt => new WorkOrderHistoryProgress
                                    {
                                        Status = dt.Status.GetDescription(),
                                        ReasonForChange = dt.ReasonForChange,
                                        ReasonForChangeDescription = dt.ReasonForChangeDescription,
                                        UpdateTime = dt.CreateTime,
                                        Urgent = dt.Urgent == DataModels.Enums.GeneralEnum.Status.Enable
                                    })];
                }
                return Success(wodre);
            }

            List<GetWorkOrderRapidDto> wod = db.Queryable<WorkOrderRapid, Projects, Material>((wot, p, ml) => new object[]
            {
                JoinType.Left,wot.ProjectId == p.UUID,
                JoinType.Left,wot.MaterialUUID ==ml.UUID
            })
                .Where(wot => wot.ProcessorId == UserUUID || wot.RequesterId == UserUUID)
                .WhereIF(info.ProjectId.HasValue, wot => wot.ProjectId == info.ProjectId)
                .WhereIF(info.StartTime.HasValue, wot => wot.CreateTime >= info.StartTime)
                .WhereIF(info.EndTime.HasValue, wot => wot.CreateTime <= info.EndTime)
                .WhereIF(info.Status.Count != 0, wot => info.Status.Contains(wot.Status))
                .Select((wot, p, ml) => new GetWorkOrderRapidDto
                {
                    WorkOrderId = wot.UUID,
                    ProjectName = p.ProjectName,
                    Type = wot.Type,
                    Status = wot.Status,
                    Urgent = wot.Urgent,
                    CreateTime = wot.CreateTime,
                    OrderNo = wot.OrderNo,
                    Description = wot.Description,
                    Phone = wot.Phone,
                    Urls = new List<string>(),
                    material = ml.Name
                })
                .ToList()
                ;

            // 如果当前人员为  济和医院工单领导查看员 则 显示出所有的 待分配工单
            ResponseModel rm2 = _userService.WhetherPersonSpecifiedRole("济和医院工单领导查看员");
            if ((bool)rm2.Data)
            {
                wod.AddRange(db.Queryable<WorkOrderRapid, Projects>((wot, p) => new object[]
                   {
                            JoinType.Left,wot.ProjectId == p.UUID
                   })
                   .WhereIF(info.ProjectId.HasValue, wot => wot.ProjectId == info.ProjectId)
                   .WhereIF(info.StartTime.HasValue, wot => wot.CreateTime >= info.StartTime)
                   .WhereIF(info.EndTime.HasValue, wot => wot.CreateTime <= info.EndTime)
                   .WhereIF(info.Status.Count != 0, wot => info.Status.Contains(wot.Status))
                   .Select((wot, p) => new GetWorkOrderRapidDto
                   {
                       WorkOrderId = wot.UUID,
                       ProjectName = p.ProjectName,
                       Type = wot.Type,
                       Status = wot.Status,
                       Urgent = wot.Urgent,
                       CreateTime = wot.CreateTime,
                       OrderNo = wot.OrderNo,
                       Description = wot.Description,
                       Phone = wot.Phone,
                       Urls = new List<string>()
                   })
                   .ToList()
                );
            }

            // 如果当前人员为  济和医院工单接单员工程类 则 显示出所有的 分配人为工程类工单
            ResponseModel rm5 = _userService.WhetherPersonSpecifiedRole("济和医院工单接单员工程类");
            if (rm5.Data != null)
            {
                if ((bool)rm5.Data)
                {
                    wod.AddRange(db.Queryable<WorkOrderRapid, Projects, WorkOrderType, Material>((wot, p, wott, ml) => new object[]
                       {
                            JoinType.Left,wot.ProjectId == p.UUID,
                            JoinType.Left,wot.TypeId ==wott.Id,
                              JoinType.Left,wot.MaterialUUID ==ml.UUID
                       })
                       .LeftJoin<WorkOrderType>((wot, p, wott, ml, wott1) => wott.ParentId == wott1.Id)
                       .Where(wot => wot.ProcessorId == UserUUID || wot.Status == WorkOrderRapidStatus.New)
                       .Where((wot, p, wott) => wott.ParentId == 47)
                       .WhereIF(info.ProjectId.HasValue, wot => wot.ProjectId == info.ProjectId)
                       .WhereIF(info.StartTime.HasValue, wot => wot.CreateTime >= info.StartTime)
                       .WhereIF(info.EndTime.HasValue, wot => wot.CreateTime <= info.EndTime)
                       .WhereIF(info.Status.Count != 0, wot => info.Status.Contains(wot.Status))
                       .Select((wot, p, wott, ml, wott1) => new GetWorkOrderRapidDto
                       {
                           WorkOrderId = wot.UUID,
                           ProjectName = p.ProjectName,
                           Type = wott1.Name + "-" + wot.Type,
                           Status = wot.Status,
                           Urgent = wot.Urgent,
                           CreateTime = wot.CreateTime,
                           OrderNo = wot.OrderNo,
                           Description = wot.Description,
                           Phone = wot.Phone,
                           Urls = new List<string>(),
                           material = ml.Name
                       })
                       .ToList()
                    );
                }
            }
            // 如果当前人员为  济和医院工单接单员(环境、秩序、其他自动派单)  则 显示出所有的 分配人为自己工单
            ResponseModel rm3 = _userService.WhetherPersonSpecifiedRole("济和医院工单接单员");
            if (rm3.Data != null)
            {
                if ((bool)rm3.Data)
                {

                    wod.AddRange(db.Queryable<WorkOrderRapid, Projects, WorkOrderType, Material>((wot, p, wott, ml) => new object[]
                       {
                            JoinType.Left,wot.ProjectId == p.UUID,
                            JoinType.Left,wot.TypeId ==wott.Id,
                            JoinType.Left,wot.MaterialUUID ==ml.UUID
                       })
                        .LeftJoin<WorkOrderType>((wot, p, wott, ml, wott1) => wott.ParentId == wott1.Id)
                       .Where(wot => wot.ProcessorId == UserUUID || wot.Status == WorkOrderRapidStatus.New)
                       .Where((wot, p, wott) => wott.ParentId != 47)
                       .WhereIF(info.ProjectId.HasValue, wot => wot.ProjectId == info.ProjectId)
                       .WhereIF(info.StartTime.HasValue, wot => wot.CreateTime >= info.StartTime)
                       .WhereIF(info.EndTime.HasValue, wot => wot.CreateTime <= info.EndTime)
                       .WhereIF(info.Status.Count != 0, wot => info.Status.Contains(wot.Status))
                       .Select((wot, p, wott, ml, wott1) => new GetWorkOrderRapidDto
                       {
                           WorkOrderId = wot.UUID,
                           ProjectName = p.ProjectName,
                           Type = wott1.Name + "-" + wot.Type,
                           Status = wot.Status,
                           Urgent = wot.Urgent,
                           CreateTime = wot.CreateTime,
                           OrderNo = wot.OrderNo,
                           Description = wot.Description,
                           Phone = wot.Phone,
                           Urls = new List<string>(),
                           material = ml.Name

                       })
                       .ToList()
                    );
                }
            }
            // 如果当前人员为  济和医院工单审核员 则 显示出所有的 已解决工单
            ResponseModel rm4 = _userService.WhetherPersonSpecifiedRole("济和医院工单审核员");
            if (rm4.Data != null)
            {
                if ((bool)rm4.Data)
                {
                    wod.AddRange(db.Queryable<WorkOrderRapid, Projects, Material>((wot, p, ml) => new object[]
                       {
                            JoinType.Left,wot.ProjectId == p.UUID,
                            JoinType.Left,wot.MaterialUUID ==ml.UUID
                       })
                        .Where(wot => wot.Status == WorkOrderRapidStatus.Resolved || wot.Status == WorkOrderRapidStatus.Closed)
                       .WhereIF(info.ProjectId.HasValue, wot => wot.ProjectId == info.ProjectId)
                       .WhereIF(info.StartTime.HasValue, wot => wot.CreateTime >= info.StartTime)
                       .WhereIF(info.EndTime.HasValue, wot => wot.CreateTime <= info.EndTime)
                       .WhereIF(info.Status.Count != 0, wot => info.Status.Contains(wot.Status))
                       .Select((wot, p, ml) => new GetWorkOrderRapidDto
                       {
                           WorkOrderId = wot.UUID,
                           ProjectName = p.ProjectName,
                           Type = wot.Type,
                           Status = wot.Status,
                           Urgent = wot.Urgent,
                           CreateTime = wot.CreateTime,
                           OrderNo = wot.OrderNo,
                           Description = wot.Description,
                           Phone = wot.Phone,
                           Urls = new List<string>(),
                           material = ml.Name
                       })
                       .ToList()
                    );
                }
            }

            // 去重
            wod = wod.GroupBy(x => x.WorkOrderId).Select(g => g.First()).ToList();
            wod = wod.OrderByDescending(wot => wot.CreateTime).ToList();
            List<GetWorkOrderrAPIDResponse> res = [.. wod.Select(dto => new GetWorkOrderrAPIDResponse
            {
                WorkOrderId = dto.WorkOrderId,
                ProjectName = dto.ProjectName,
                Type = dto.Type,
                Status = dto.Status,
                Urgent = dto.Urgent.ObjToBool(),
                CreateTime = dto.CreateTime,
                OrderNo = dto.OrderNo,
                Description = dto.Description,
                Phone = dto.Phone,
                Urls = new List<string>(),
                material =dto.material
            })];
            return Success(res);
        }

        /// <summary>
        /// 获取工单详情历史记录
        /// </summary>
        /// <param name="workorderid"></param>
        /// <returns></returns>
        public ResponseModel GetWorkOrderHistory(Guid workorderid)
        {
            GetWorkOrderRapidHistoryDto wot = db.Queryable<WorkOrderRapid, HousingBasic>((wot, hb) => new object[]
            {
                JoinType.Left,wot.HouseUUID == hb.UUID
            })
                .Where(wot => wot.UUID == workorderid)
                .Select((wot, hb) => new GetWorkOrderRapidHistoryDto
                {
                    OrderNo = wot.OrderNo,
                    PropertiesUUID = hb.PropertiesUUID,
                    Phone = wot.Phone,
                    CreateTime = wot.CreateTime,
                    Description = wot.Description,
                    Status = wot.Status,
                    Urgent = wot.Urgent
                }).First();
            if (wot == null)
            {
                return Error("工单不存在");
            }
            var cuser = db.Queryable<Customer>().Where(c => c.Tel1 == wot.Phone).First();
            var pp = db.Queryable<CustomerHouseRelation>().Where(x => x.CustId == cuser.CustId).First();

            //Properties pp = db.Queryable<Properties>().Where(pp => pp.UUID == Guid.Parse(wot.PropertiesUUID)).First();
            List<string> urls = db.Queryable<Attachment>().Where(atc => atc.BusinessId == workorderid).Select(atc => atc.Url).ToList();
            List<WorkOrderHistory> woth = db.Queryable<WorkOrderHistory>().Where(wot => wot.WorkOrderUUID == workorderid).OrderBy(wot => wot.CreateTime, OrderByType.Desc).ToList();

            GetWorkOrderHistoryResponse res = new()
            {
                OrderNo = wot.OrderNo,
                PropertiesUUID = wot.PropertiesUUID,
                Phone = wot.Phone,
                Urgent = wot.Urgent == DataModels.Enums.GeneralEnum.Status.Enable,
                CreateTime = wot.CreateTime,
                Description = wot.Description,
                Status = wot.Status.GetDescription(),
                FullAddress = pp.ResourceName,
                Urls = urls,
                Progress = [.. woth.Select(dt => new WorkOrderHistoryProgress
                {
                    Status = dt.Status.GetDescription(),
                    UpdateTime = dt.UpdateTime,
                    Urgent = dt.Urgent == DataModels.Enums.GeneralEnum.Status.Enable
                })]
            };

            return Success(res);
        }
        /// <summary>
        ///  通过项目获取物料类型
        /// </summary>
        /// <param name="projectUUID"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ResponseModel GetMaterialByProjectUUID(string projectUUID)
        {
            var res = db.Queryable<Material, Warehouse>((m, w) => new object[] { JoinType.Left, m.WarehouseUUID == w.UUID })
                .Where((m, w) => w.ProjectSUUID == projectUUID)
                .Select((m, w) => new {
                    m.UUID,
                    m.Name
                }).ToList();
            return Success(res);
        }
    }
}
